package api

import (
	"bytes"
	"encoding/json"
	"gdfs-service/conf"
	"gdfs-service/controller/vo"
	"gdfs-service/db"
	"gdfs-service/logcat"
	"gdfs-service/utils"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"strings"
)

//func PostSyncData(s ao.SyncDb,ip,port string) vo.Result {
//	if ip == utils.GetInternetIp(){
//		ip = utils.GetLocalIPaddress()
//	}
//	url:="http://"+ip+":"+port+"/gdfs/api/data/fullupdate"
//	logcat.GetLog().Sugar().Info(url)
//	//client := &http.Client{}
//	bytesData, _ := json.Marshal(s)
//	var result vo.Result
//	resp, _ := http.Post(url,"application/json",bytes.NewReader(bytesData))
//	//resp, _ := client.Do(req)
//	logcat.GetLog().Sugar().Info("###返回:",resp)
//	if resp == nil{
//		return result
//	}
//	body, _ := ioutil.ReadAll(resp.Body)
//
//	err:=json.Unmarshal(body,&result)
//	if err != nil{
//		logcat.GetLog().Info("###PostSyncData---json解析返回结果异常")
//		return result
//	}
//	return result
//}

//发送需要同步的文件
func PostNultipartFile(fileinfo db.FileInfo, ip, port string) vo.Result {
	if ip == utils.GetInternetIp() {
		ip = utils.GetLocalIPaddress()
	}
	var result vo.Result
	url := "http://" + ip + ":" + port + "/gdfs/api/file/syncfile"
	s := strings.Split(fileinfo.FilePath, "/")
	filepath := conf.GetStorePath() + s[len(s)-2] + "/" + fileinfo.FileName
	file, err := os.Open(filepath)
	if err != nil {
		logcat.Info("###SendSyncFile open file err:", err)
	}
	defer file.Close()
	buf := new(bytes.Buffer)
	w := multipart.NewWriter(buf)
	w.WriteField("fileKey", fileinfo.FileKey)
	w.WriteField("fileName", fileinfo.FileName)
	w.WriteField("fileOriginalName", fileinfo.FileOriginalName)
	w.WriteField("content", s[len(s)-2])
	w.WriteField("fileSuffixName", fileinfo.FileSuffixName)
	fw, _ := w.CreateFormFile("files", fileinfo.FileOriginalName)
	if _, err = io.Copy(fw, file); err != nil {
		logcat.Info("###SendSyncFile copy file err:", err)
		result.Fail(err.Error(), "-1", nil)
		return result
	}
	w.Close()
	req, nerr := http.NewRequest("POST", url, buf)
	if nerr != nil {
		logcat.Info("###SendSyncFile new req err:", nerr)
		result.Fail(nerr.Error(), "-1", nil)
		return result
	}
	req.Header.Set("Content-Type", w.FormDataContentType())

	resp, rerr := http.DefaultClient.Do(req)
	if rerr != nil {
		logcat.Info("###SendSyncFile req err:", rerr)
		result.Fail(rerr.Error(), "-1", nil)
		return result
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	jsonerr := json.Unmarshal(body, &result)
	if jsonerr != nil {
		logcat.Info("###PostSyncData---json解析返回结果异常")
		result.Fail(jsonerr.Error(), "-1", nil)
		return result
	}
	return result
}
